package com.share51.novel.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 异步线程池配置
 *
 * @author gb
 */
@Setter
@Getter
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "com.share51.async")
public class AsyncPoolConfig implements AsyncConfigurer {

    /**
     * 核心线程数
     */
    private int corePoolSize=4;
    /**
     * 最大线程数
     */
    private int maxPoolSize=10;
    /**
     * 队列大小
     */
    private int queueCapacity=500;
    /**
     * 线程最大空闲时间
     * 允许的空闲时间,当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
     */
    private int keepAliveSeconds=60;
    /**
     * 线程日志名称前缀
     */
    private String threadNamePrefix="async-service-";
    /**
     * 等待所有线程执行完
     */
    private boolean waitForTasksToCompleteOnShutdown=true;
    /**
     * 等待所有线程执行完,等待时间
     */
    private int awaitTerminationSeconds=60;

    @Bean
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setThreadNamePrefix(threadNamePrefix);
        executor.setWaitForTasksToCompleteOnShutdown(waitForTasksToCompleteOnShutdown);
        executor.setAwaitTerminationSeconds(awaitTerminationSeconds);
        executor.setRejectedExecutionHandler(
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncExceptionHandler();
    }

    /**
     * 此工具仅处理无返回的异步任务触发的异常
     */
    @SuppressWarnings("all")
    class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler {

        @Override
        public void handleUncaughtException(Throwable throwable,
                                            Method method,
                                            Object... objects) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                log.error("异常任务处理失败了: {}, Method: {}, Param: {}",
                        throwable.getMessage(), method.getName(),
                        mapper.writeValueAsString(of(objects)));
                throwable.printStackTrace();
            } catch (JsonProcessingException e) {
                log.error("异常任务处理记录日志失败了,日志：{}",e);
            }
        }

        private List<Object> of(Object... objects) {
            return Stream.of(objects).collect(Collectors.toList());
        }
    }

}
